﻿using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Nest;
using ServiceCore.Token;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static ServiceCore.Tool.ES.Es_knowledge;

namespace ServiceCore.Tool.ES
{
    public interface IEs_knowledge
    {  
        /// <summary>
        /// 数据添加
        /// </summary>
        /// <param name="logmod"></param>
        /// <returns></returns>
        object Add_Item(knowledge_base logmod);
        /// <summary>
        /// 数据更新
        /// </summary>
        /// <param name="update_mod"></param>
        /// <returns></returns>
        object Update_row(knowledge_base update_mod);
        /// <summary>
        /// 查询符合条件的项
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        object Es_query(knowledge_search query, string uid, Func<SortDescriptor<knowledge_base>, IPromise<IList<ISort>>> diy_sort = null);

        object Es_query_for_kanban(knowledge_search query, string uid,ref long total, Func<SortDescriptor<knowledge_base>, IPromise<IList<ISort>>> diy_sort = null);

        long Es_query_isread_count(knowledge_search query, string read_id); 
        /// <summary>
        /// 获取指定条件文件数量
        /// </summary>
        /// <param name="query"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        long Es_query_count(knowledge_search query, string uid);
        object Es_delete(string Id);
        /// <summary>
        /// 根据ID获取文章信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        knowledge_base get_es_model(string id);
    }
    public class Es_knowledge: IEs_knowledge
    {
        private ConnectionSettings setting_Config
        {
            get
            {
                //var uris = new Uri[] { new Uri("http://47.106.34.163:9422") };
                //var connectionPool = new SniffingConnectionPool(uris);
                //var settings = new ConnectionSettings(connectionPool).DefaultIndex("rk_es");
                var uri = new Uri(AppSettingConfig["ES_Knowledge:uri"].ToString());
                var settings = new ConnectionSettings(uri);
                //验证 未开启
                //settings.BasicAuthentication("username", "password");
                //验证证书
                //settings.ClientCertificate("");
                //settings.ClientCertificates(new X509CertificateCollection());
                //settings.ServerCertificateValidationCallback(); 
                //开启 第一次使用时进行嗅探，需链接池支持
                //settings.SniffOnStartup(false); 
                //链接最大并发数
                //settings.ConnectionLimit(80);
                //标记为死亡节点的超时时间
                //settings.DeadTimeout(new TimeSpan(10000));
                //settings.MaxDeadTimeout(new TimeSpan(10000));
                //最大重试次数
                //settings.MaximumRetries(5);
                //重试超时时间 默认是RequestTimeout
                //settings.MaxRetryTimeout(new TimeSpan(50000));
                //禁用代理自动检测
                //settings.DisableAutomaticProxyDetection(true);

                //禁用ping 第一次使用节点或使用被标记死亡的节点进行ping
                settings.DisablePing(false);
                //ping 超时设置
                //settings.PingTimeout(new TimeSpan(10000));
                //选择节点
                //settings.NodePredicate(node =>
                //{
                //    
                //        return true;
                //    
                //});
                //默认操作索引
                //settings.DefaultIndex("");
                //字段名规则 与model字段同名
                //settings.DefaultFieldNameInferrer(name => name);
                //根据Type 获取类型名
                //settings.DefaultTypeNameInferrer(name => name.Name);
                //请求超时设置
                //settings.RequestTimeout(new TimeSpan(10000));
                //调试信息
                settings.DisableDirectStreaming(true);
                //调试信息
                //settings.EnableDebugMode((apiCallDetails) =>
                //{
                //    //请求完成 返回 apiCallDetails

                //});
                //抛出异常 默认false，错误信息在每个操作的response中
                settings.ThrowExceptions(true);
                //settings.OnRequestCompleted(apiCallDetails =>
                //{
                //    //请求完成 返回 apiCallDetails
                //});
                //settings.OnRequestDataCreated(requestData =>
                //{
                //    //请求的数据创建完成 返回请求的数据

                //}); 
                return settings;
            }
        }
        private ElasticClient ES_client = null;// new ElasticClient(setting_Config);
        private Es_Web_Set EsWebSet = new Es_Web_Set();
        /// <summary>
        /// 定义ES当前使用的index和type设定
        /// </summary>
        private class Es_Web_Set
        {
            /// <summary>
            /// ES 索引
            /// </summary>
            public string Index { get; set; }
            /// <summary>
            /// ES类型
            /// </summary>
            public string Type { get; set; }
            /// <summary>
            /// 别名
            /// </summary>
            public string Alias { get; set; }
        }

        public string ES_IndexAndType_Set { get { return AppSettingConfig["ES_Knowledge:I_T"].ToString(); } }
        private readonly IConfiguration AppSettingConfig;
        private readonly ISnowflake_Helper _getid;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ITokenUser_Service _user; 
        public Es_knowledge(IConfiguration configuration, ISnowflake_Helper getid, IHttpContextAccessor httpContextAccessor, ITokenUser_Service user)
        {
            AppSettingConfig = configuration;
            _getid = getid;
            _httpContextAccessor = httpContextAccessor;
            _user = user;
            if (ES_client == null)
            {
                ES_client = new ElasticClient(setting_Config);
            }
            var es_web = ES_IndexAndType_Set.Split(':');
            EsWebSet.Index = es_web[0];
            EsWebSet.Type = es_web[1];
            EsWebSet.Alias = es_web[2];
            
        }

        /// <summary>
        /// 定义log文件模型
        /// </summary>
        [ElasticsearchType(Name = "knowledge_base", IdProperty = "Id")]
        public class knowledge_base
        {
            [Keyword(Name = "Id", Index = true)]
            public string Id { get; set; }
            /// <summary>
            /// keyword 不分词
            /// </summary>
            [Keyword(Name = "type_a", Index = true)]
            public string type_a { get; set; }
            /// <summary>
            /// keyword 不分词
            /// </summary>
            [Keyword(Name = "type_b", Index = true)]
            public string type_b { get; set; }
            /// <summary>
            /// keyword 不分词
            /// </summary>
            [Keyword(Name = "type_c", Index = true)]
            public string type_c { get; set; }
            /// <summary>
            /// keyword 不分词
            /// </summary>
            [Keyword(Name = "type_a_name", Index = false)]
            public string type_a_name { get; set; }
            /// <summary>
            /// keyword 不分词
            /// </summary>
            [Keyword(Name = "type_b_name", Index = false)]
            public string type_b_name { get; set; }
            /// <summary>
            /// keyword 不分词
            /// </summary>
            [Keyword(Name = "type_c_name", Index = false)]
            public string type_c_name { get; set; }
            /// <summary>
            /// text 分词,Analyzer = "ik_max_word"
            /// </summary>
            [Text(Name = "title", Index = true, Analyzer = "jieba_index", SearchAnalyzer = "jieba_index")]
            public string title { get; set; }
            /// <summary>
            /// text 分词,Analyzer = "ik_max_word"
            /// </summary>
            [Text(Name = "content", Index = true, Analyzer = "jieba_index", SearchAnalyzer = "jieba_index")]
            public string content { get; set; }
            /// <summary>
            /// text 分词,Analyzer = "ik_max_word"
            /// </summary>
            [Text(Name = "content_des", Index = true, Analyzer = "jieba_index", SearchAnalyzer = "jieba_index")]
            public string content_des { get; set; }
            /// <summary>
            /// 上下架状态
            /// </summary>
            [Number(NumberType.Integer, Name = "state")]
            public int state { get; set; }
            /// <summary>
            /// 是否被删除
            /// </summary>
            [Boolean(Name = "isdelete")]
            public bool isdelete { get; set; }
            /// <summary>
            /// 添加时间
            /// </summary>
            [Date(Name = "add_time")]
            public DateTime add_time { get; set; }

            /// <summary>
            /// 显示时间
            /// </summary>
            [Date(Name = "show_time")]
            public DateTime? show_time { get; set; }

            /// <summary>
            /// keyword 不分词
            /// </summary>
            [Keyword(Name = "author", Index = true)]
            public string author { get; set; }
            /// <summary>
            /// 上下架状态
            /// </summary>
            [Number(NumberType.Integer, Name = "hit")]
            public int hit { get; set; } = 0;

            /// <summary>
            /// keyword 不分词
            /// </summary>
            [Keyword(Name = "add_user", Index = true)]
            public string add_user { get; set; }

            /// <summary>
            /// 是否rk私有
            /// </summary>
            [Boolean(Name = "is_rk_private")]
            public bool is_rk_private { get; set; } = false;
            /// <summary>
            /// 编辑时间
            /// </summary>
            [Date(Name = "last_edit_time")]
            public DateTime last_edit_time { get; set; }
            /// <summary>
            /// 其他资源项目，例如封面图之类的地址
            /// </summary>
            [Keyword(Name = "other_resources", Index = true)]
            public string other_resources { get; set; }
            /// <summary>
            /// 是否已经分享
            /// </summary>
            [Boolean(Name = "is_share")]
            public bool is_share { get; set; }
            /// <summary>
            /// 分享过期时间
            /// </summary>
            [Date(Name = "share_end_time")]
            public DateTime? share_end_time { get; set; }
            /// <summary>
            /// 是否永久
            /// </summary>
            [Boolean(Name = "is_long")]
            public bool is_long { get; set; }
            [Number(NumberType.Integer, Name = "set_params")]
            /// <summary>
            /// 设置参数
            /// </summary>
            public int set_params { get; set; } 
            /// <summary>
            /// 已读人
            /// </summary>
            [Nested(Name = "read_list")]
            public List<read_item> read_list { get; set; }  
        }

        public class read_item
        {
            public string read_id { get; set; }
        }
        /// <summary>
        /// 添加日志信息  如果index不存在 则创建一个新的
        /// </summary>
        public object Add_Item(knowledge_base logmod)
        {
            try
            {

                if (!ES_client.IndexExists(EsWebSet.Index).Exists)
                {
                    //基本配置
                    IIndexState indexState = new IndexState()
                    {
                        Settings = new IndexSettings()
                        {
                            NumberOfReplicas = 0,//副本数 因为目前都是单节点在跑  也没有服务器做这个架构
                            NumberOfShards = 5,//分片数
                             
                        }
                    };
                    //创建并Mapping
                    var create = ES_client.CreateIndex(EsWebSet.Index, p =>
                            p.InitializeUsing(indexState)
                            .Mappings(m => m.Map<knowledge_base>(mp => mp.AutoMap())).Aliases(s => s.Alias(EsWebSet.Alias)));

                }
                //写入数据，指定索引
                var result = ES_client.Index(logmod, s => s.Index(EsWebSet.Index).Type(EsWebSet.Type).Id(logmod.Id).Refresh(Elasticsearch.Net.Refresh.True));
                return new
                {
                    result.Shards,
                    result.ApiCall.HttpStatusCode,
                    result.DebugInformation,
                    result.ServerError
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public knowledge_base get_es_model(string id)
        {
            try {
                var result = ES_client.Search<knowledge_base>(s =>
                {
                    return s.Index(EsWebSet.Index).Type(EsWebSet.Type).Query(a =>
                    {
                        return a.Bool(z => z.Must(sq => sq.Term(c => c.Field(d => d.Id).Value(id))));
                    })
                    .From(0) //跳过的数据个数
                    .Size(1);//返回数据个数
                });
                return result.Documents.FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="update_mod"></param>
        /// <returns></returns>
        public object Update_row(knowledge_base update_mod)
        {
            try
            {
                DocumentPath<knowledge_base> deletePath = new DocumentPath<knowledge_base>(update_mod.Id).Index(EsWebSet.Index).Type(EsWebSet.Type);
                var response = ES_client.Update(deletePath, (p) => p.Doc(update_mod).Refresh(Elasticsearch.Net.Refresh.True));
                return new
                {
                    response.ShardsHit,
                    response.ApiCall.HttpStatusCode,
                    response.DebugInformation,
                    response.ServerError
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 查询符合条件的数据
        /// </summary>
        public object Es_query(knowledge_search query,string uid, Func<SortDescriptor<knowledge_base>, IPromise<IList<ISort>>> diy_sort=null)
        {
            try
            {
                string search_key = "";
                if (!string.IsNullOrWhiteSpace(query.search_title))
                {
                    search_key = Regex.Replace(query.search_title, @"\s", "");//去掉搜索字符串中的奇奇怪怪的东西 
                }
                //设置must条件
                var mustQuerys = new List<Func<QueryContainerDescriptor<knowledge_base>, QueryContainer>>();
                if (!string.IsNullOrWhiteSpace(search_key))
                {
                    mustQuerys.Add(sq => sq.Match(b => b.Analyzer("jieba_index").Field(c => c.content_des).Query(search_key)) || sq.Match(b => b.Analyzer("jieba_index").Field(c => c.title).Query(search_key)));
                }
                if (query.state.HasValue)
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.state).Value(query.state.Value)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_a))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_a).Value(query.type_a)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_b))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_b).Value(query.type_b)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_c))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_c).Value(query.type_c)));
                }
                if (!string.IsNullOrWhiteSpace(uid))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.add_user).Value(uid)));
                }
                //排序
                Func<SortDescriptor<knowledge_base>, IPromise<IList<ISort>>> sortDesc;
                if (diy_sort != null)
                {
                    sortDesc = diy_sort;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(uid))
                    {
                        sortDesc = sd =>
                        {
                            //根据分值排序
                            sd.Descending(SortSpecialField.Score);
                            //排序 
                            sd.Descending(d => d.add_time);
                            return sd;
                        };
                    }
                    else {
                        sortDesc = sd =>
                        {
                            //排序 
                            sd.Descending(d => d.last_edit_time);
                            return sd;
                        };
                    }
                     
                }
                //设置高亮
                var hight_params = new Func<HighlightFieldDescriptor<knowledge_base>, IHighlightField>[] {
                     new Func<HighlightFieldDescriptor<knowledge_base>, IHighlightField>(c =>
                    {
                        return c.Field(d => d.content_des).FragmentSize(50).PreTags("<span style='color:red;'>").PostTags("</span>");  //.Type(HighlighterType.Plain);
                    }),
                     new Func<HighlightFieldDescriptor<knowledge_base>, IHighlightField>(c =>
                    {
                        return c.Field(d => d.title).FragmentSize(1024).PreTags("<span style='color:red;'>").PostTags("</span>");  //.Type(HighlighterType.Plain);
                    }),
                };
                var result = ES_client.Search<knowledge_base>(s =>
                {
                    return s.Index(EsWebSet.Index).Type(EsWebSet.Type).Query(a =>
                    {
                        return a.Bool(z => z.Must(mustQuerys));
                    })
                    .Highlight(a=>a.Fields(hight_params)) 
                    .Sort(sortDesc)
                    .From((query.page - 1) * query.pagesize) //跳过的数据个数
                    .Size(query.pagesize);//返回数据个数
                });

                return new
                {
                    result.Total,
                    rows = from o in result.Hits
                           select new
                           {
                               Highlights = !o.Highlights.Where(s => s.Key == "title").Any() ? o.Source.title :
                                            o.Highlights.Where(s => s.Key == "title").FirstOrDefault().Value.Highlights.Any() ?
                                               string.IsNullOrWhiteSpace(string.Join("....", o.Highlights.Where(s => s.Key == "title").FirstOrDefault().Value.Highlights)) ?
                                                    o.Source.title : string.Join("....", o.Highlights.Where(s => s.Key == "title").FirstOrDefault().Value.Highlights)//.FirstOrDefault()
                                                    : o.Source.title,
                               Highlights_des = !o.Highlights.Where(s => s.Key == "content_des").Any() ? "" :
                                            o.Highlights.Where(s => s.Key == "content_des").FirstOrDefault().Value.Highlights.Any() ?
                                                string.Join("....", o.Highlights.Where(s => s.Key == "content_des").FirstOrDefault().Value.Highlights) //.FirstOrDefault()
                                                    : "",
                               o.Score,
                               o.Source.type_a_name,
                               o.Source.type_b_name,
                               o.Source.type_c_name,
                               o.Source.title,
                               o.Source.state,
                               state_str = o.Source.state == 0 ? "草稿箱" : "知识库",
                               o.Source.add_time,
                               o.Source.show_time,
                               o.Source.last_edit_time,
                               o.Source.is_rk_private,
                               Es_id = o.Id,
                               o.Source.Id,
                               o.Source.is_share,
                               o.Source.share_end_time,
                               o.Source.is_long,
                               o.Source.set_params
                           }
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }




        /// <summary>
        /// 查询符合条件的数据
        /// </summary>
        public object Es_query_for_kanban(knowledge_search query, string uid, ref long total, Func<SortDescriptor<knowledge_base>, IPromise<IList<ISort>>> diy_sort = null)
        {
            try
            {
                string search_key = "";
                if (!string.IsNullOrWhiteSpace(query.search_title))
                {
                    search_key = Regex.Replace(query.search_title, @"\s", "");//去掉搜索字符串中的奇奇怪怪的东西 
                }
                //设置must条件
                var mustQuerys = new List<Func<QueryContainerDescriptor<knowledge_base>, QueryContainer>>();
                if (!string.IsNullOrWhiteSpace(search_key))
                {
                    mustQuerys.Add(sq => sq.Match(b => b.Analyzer("jieba_index").Field(c => c.content_des).Query(search_key)) || sq.Match(b => b.Analyzer("jieba_index").Field(c => c.title).Query(search_key)));
                }
                if (query.state.HasValue)
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.state).Value(query.state.Value)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_a))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_a).Value(query.type_a)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_b))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_b).Value(query.type_b)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_c))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_c).Value(query.type_c)));
                } 
                //排序
                Func<SortDescriptor<knowledge_base>, IPromise<IList<ISort>>> sortDesc;
                if (diy_sort != null)
                {
                    sortDesc = diy_sort;
                }
                else
                {
                    sortDesc = sd =>
                    {
                        //根据分值排序
                        sd.Descending(SortSpecialField.Score);
                        //排序 
                        sd.Descending(d => d.show_time);
                        return sd;
                    };
                }
                //设置高亮
                var hight_params = new Func<HighlightFieldDescriptor<knowledge_base>, IHighlightField>[] {
                     new Func<HighlightFieldDescriptor<knowledge_base>, IHighlightField>(c =>
                    {
                        return c.Field(d => d.content_des).FragmentSize(50).PreTags("<span style='color:red;'>").PostTags("</span>");  //.Type(HighlighterType.Plain);
                    }),
                     new Func<HighlightFieldDescriptor<knowledge_base>, IHighlightField>(c =>
                    {
                        return c.Field(d => d.title).FragmentSize(1024).PreTags("<span style='color:red;'>").PostTags("</span>");  //.Type(HighlighterType.Plain);
                    }),
                };
                var result = ES_client.Search<knowledge_base>(s =>
                {
                    return s.Index(EsWebSet.Index).Type(EsWebSet.Type).Query(a =>
                    {
                        return a.Bool(z => z.Must(mustQuerys));
                    })
                    .Highlight(a => a.Fields(hight_params))
                    .Sort(sortDesc)
                    .From((query.page - 1) * query.pagesize) //跳过的数据个数
                    .Size(query.pagesize);//返回数据个数
                });
                total = result.Total;
                return new
                {
                    result.Total,
                    rows = from o in result.Hits
                           select new
                           {
                               Highlights = !o.Highlights.Where(s => s.Key == "title").Any() ? o.Source.title :
                                            o.Highlights.Where(s => s.Key == "title").FirstOrDefault().Value.Highlights.Any() ?
                                               string.IsNullOrWhiteSpace(string.Join("....", o.Highlights.Where(s => s.Key == "title").FirstOrDefault().Value.Highlights)) ?
                                                    o.Source.title : string.Join("....", o.Highlights.Where(s => s.Key == "title").FirstOrDefault().Value.Highlights)//.FirstOrDefault()
                                                    : o.Source.title,
                               Highlights_des = !o.Highlights.Where(s => s.Key == "content_des").Any() ? "" :
                                            o.Highlights.Where(s => s.Key == "content_des").FirstOrDefault().Value.Highlights.Any() ?
                                                string.Join("....", o.Highlights.Where(s => s.Key == "content_des").FirstOrDefault().Value.Highlights) //.FirstOrDefault()
                                                    : "",
                               o.Score,
                               o.Source.type_a_name,
                               o.Source.type_b_name,
                               o.Source.type_c_name,
                               o.Source.title,
                               o.Source.state,
                               state_str = o.Source.state == 0 ? "草稿箱" : "知识库",
                               o.Source.add_time,
                               o.Source.show_time,
                               o.Source.last_edit_time,
                               o.Source.is_rk_private,
                               Es_id = o.Id,
                               o.Source.Id,
                               o.Source.is_share,
                               o.Source.share_end_time,
                               o.Source.is_long,
                               o.Source.set_params,
                               is_read = o.Source.read_list == null ? false : o.Source.read_list.Where(s => s.read_id == uid).Any(),
                               is_new = o.Source.show_time >= DateTime.Now.AddMonths(-1)
                           }
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 查询符合条件的数据数量
        /// </summary>
        /// <returns></returns>
        public long Es_query_count(knowledge_search query, string uid) {
            try
            {
                string search_key = "";
                if (!string.IsNullOrWhiteSpace(query.search_title))
                {
                    search_key = Regex.Replace(query.search_title, @"\s", "");//去掉搜索字符串中的奇奇怪怪的东西 
                }
                //设置must条件
                var mustQuerys = new List<Func<QueryContainerDescriptor<knowledge_base>, QueryContainer>>();
                if (!string.IsNullOrWhiteSpace(search_key))
                {
                    mustQuerys.Add(sq => sq.Match(b => b.Analyzer("jieba_index").Field(c => c.content_des).Query(search_key)) || sq.Match(b => b.Analyzer("jieba_index").Field(c => c.title).Query(search_key)));
                }
                if (query.state.HasValue)
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.state).Value(query.state.Value)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_a))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_a).Value(query.type_a)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_b))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_b).Value(query.type_b)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_c))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_c).Value(query.type_c)));
                }
                if (!string.IsNullOrWhiteSpace(uid))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.add_user).Value(uid)));
                }
                if (!string.IsNullOrWhiteSpace(query.start_date))
                {
                    DateTime sdt;
                    if (DateTime.TryParse(query.start_date, out sdt))
                    {
                        mustQuerys.Add(sq => sq.DateRange(a => a.Field(c => c.show_time).GreaterThanOrEquals(sdt)));
                    }
                }
                var result = ES_client.Search<knowledge_base>(s =>
                {
                    return s.Index(EsWebSet.Index).Type(EsWebSet.Type).Query(a =>
                    {
                        return a.Bool(z => z.Must(mustQuerys));
                    }) 
                    .From(0) //跳过的数据个数
                    .Size(1);//返回数据个数
                }); 
                return result.Total;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 查询已读的数据量
        /// </summary>
        /// <returns></returns>
        public long Es_query_isread_count(knowledge_search query, string read_id)
        {
            try
            {
                string search_key = "";
                if (!string.IsNullOrWhiteSpace(query.search_title))
                {
                    search_key = Regex.Replace(query.search_title, @"\s", "");//去掉搜索字符串中的奇奇怪怪的东西 
                }
                //设置must条件
                var mustQuerys = new List<Func<QueryContainerDescriptor<knowledge_base>, QueryContainer>>();
                if (!string.IsNullOrWhiteSpace(search_key))
                {
                    mustQuerys.Add(sq => sq.Match(b => b.Analyzer("jieba_index").Field(c => c.content_des).Query(search_key)) || sq.Match(b => b.Analyzer("jieba_index").Field(c => c.title).Query(search_key)));
                }
                if (query.state.HasValue)
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.state).Value(query.state.Value)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_a))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_a).Value(query.type_a)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_b))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_b).Value(query.type_b)));
                }
                if (!string.IsNullOrWhiteSpace(query.type_c))
                {
                    mustQuerys.Add(sq => sq.Term(a => a.Field(c => c.type_c).Value(query.type_c)));
                }
                if (!string.IsNullOrWhiteSpace(read_id))
                {
                    mustQuerys.Add(
                       sq => sq.Nested(
                           a => a.InnerHits().Path(c => c.read_list).Query(
                               q => q.Term(
                                   p => p.Field(
                                       z => z.read_list.First().read_id).Value(read_id)
                               )
                           )
                       )
                   );
                }
                if (!string.IsNullOrWhiteSpace(query.start_date))
                {
                    DateTime sdt;
                    if (DateTime.TryParse(query.start_date, out sdt))
                    {
                        mustQuerys.Add(sq => sq.DateRange(a => a.Field(c => c.show_time).GreaterThanOrEquals(sdt)));
                    }
                }
                var result = ES_client.Search<knowledge_base>(s =>
                {
                    return s.Index(EsWebSet.Index).Type(EsWebSet.Type).Query(a =>
                    {
                        return a.Bool(z => z.Must(mustQuerys));
                    })
                    .From(0) //跳过的数据个数
                    .Size(1);//返回数据个数
                });
                return result.Total;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
         
        /// <summary>
        /// 删除知识库数据 
        /// </summary>
        /// <param name="Id"></param>
        public  object Es_delete(string id)
        {
            try
            {
                DocumentPath<knowledge_base> deletePath = new DocumentPath<knowledge_base>(id).Index(EsWebSet.Index).Type(EsWebSet.Type);
                IDeleteResponse deleresult = ES_client.Delete(deletePath, s => s.Refresh(Elasticsearch.Net.Refresh.True));
                return new
                {
                    deleresult.Shards,
                    deleresult.ApiCall.HttpStatusCode,
                    deleresult.DebugInformation,
                    deleresult.ServerError
                };
            }
            catch (Exception ex)
            {
                throw ex;
            } 
        }
    }
}